<template>
    <div class="page" ref="page">
        <!-- 顶部栏 -->
        <div class="header" :class="{ shadow: isSticky }">
            <div class="header-content">
                <h1>
                    <slot name="title">{{ name }}</slot>
                </h1>
                <div class="top-bar">
                    <button class="primary" @click="copyAll">一键复制全部代码</button>
                    <span v-show="copied" class="tip">已复制！</span>
                </div>
            </div>
        </div>

        <!-- 题目列表 -->
        <div class="page-content">
            <section v-for="(item, idx) in items" :key="idx" class="question">
                <!-- 题干（只读） -->
                <div class="question-bg">
                    <QuillEditor contentType="html" :content="item.question" :options="readOnlyOpts" />
                </div>

                <!-- 代码区（可编辑） -->
                <div class="code-wrapper">
                    <!-- <QuillEditor v-model:content="answers[idx]" contentType="text" :options="codeOpts" /> -->
                    <CodeMirrorJsTs v-model="answers[idx]" :ref="(el) => (codeEditors[idx] = el)">
                        <template #tools>
                            <div class="mini-bar">
                                <button @click="toggleRemark(idx)">
                                    {{ remarkVisible[idx] ? '隐藏备注' : '显示备注' }}
                                </button>
                                <button @click="copyOne(idx)">复制代码</button>
                                <button @click="resetOne(idx)">重置代码</button>
                                <button @click="fullscreenOne(idx)">全屏编辑</button>
                            </div>
                        </template>
                    </CodeMirrorJsTs>
                </div>
                <!-- 备注区域（默认隐藏） -->
                <div v-show="remarkVisible[idx]" class="remark-area">
                    <QuillEditor
                        contentType="html"
                        v-model:content="item.remark"
                        :options="remarkOpts"
                    />
                </div>
            </section>
        </div>
    </div>
</template>

<script setup>
import { ref, watch, nextTick, onMounted, onUnmounted } from 'vue'
import { QuillEditor } from '@vueup/vue-quill'
import '@vueup/vue-quill/dist/vue-quill.bubble.css'
import '@vueup/vue-quill/dist/vue-quill.snow.css'

import CodeMirrorJsTs from '@/components/CodeMirrorJsTs.vue'

/* ============== props & emit ============== */
const props = defineProps({
    items: { type: Array, required: true },        // [{question:'',answer:''}, ...]
    name: { type: String, required: false, default: '机考测试' }
})
const emit = defineEmits(['update:answers'])

/* ============== 阴影滚动 ============== */
const isSticky = ref(false)
const page = ref(null)
const toggleShadow = () => {
    isSticky.value = page.value.scrollTop > 60
}
const addScroll = () => page.value.addEventListener('scroll', toggleShadow)
const removeScroll = () => page.value&&page.value.removeEventListener('scroll', toggleShadow)
onMounted(() => {
    addScroll()
    toggleShadow()
})
onUnmounted(() => removeScroll())

/* ============== 编辑器配置 ============== */
const readOnlyOpts = { theme: 'snow', modules: { toolbar: false }, readOnly: true }
const codeOpts = {
    theme: 'bubble',
    modules: { toolbar: false },
    placeholder: '// 请在此处补充代码，支持本地 IDE 调通后粘贴。'
}
const remarkOpts = {
  theme: 'bubble',
  placeholder: '添加题目备注...',
  modules: {
    toolbar: [
      ['bold', 'italic', 'underline'],
      [{ list: 'ordered' }, { list: 'bullet' }],
      ['clean']
    ]
  }
}
/* ============== 答案绑定 ============== */
// 内部维护一份 answers，初始值优先用外部传入的 answer，否则给默认占位
const answers = ref(props.items.map(v => v.answer || ''))
const remarkVisible = ref(new Array(props.items.length).fill(false))
// 当父级动态修改 items 时，自动重新初始化答案数组
watch(
    () => props.items,
    newVal => {
        answers.value = newVal.map(v => v.answer || '')
        remarkVisible.value = new Array(props.items.length).fill(false)
    },
    { deep: true }
)
// 任何修改实时抛给父级
watch(answers, newVal => {
    emit('update:answers', newVal)
}, { deep: true })

/* ============== 工具函数 ============== */
const copied = ref(false)
const copyAll = () => {
    const all = answers.value.join('\n\n/* ---------- 分隔线 ---------- */\n\n')
    navigator.clipboard.writeText(all).then(() => {
        copied.value = true
        setTimeout(() => (copied.value = false), 1500)
    })
}
const copyOne = idx => navigator.clipboard.writeText(answers.value[idx])
const resetOne = idx => (answers.value[idx] = '//请在此处补充代码。\n')

const codeEditors = ref([]) // 存放所有 CodeMirror 组件实例的引用
const fullscreenOne = (idx) => {
  nextTick(() => {
    // 如果当前已是全屏，则直接退出
    if (
      document.fullscreenElement ||
      (document).webkitFullscreenElement ||
      (document).mozFullScreenElement
    ) {
      document.exitFullscreen
        ? document.exitFullscreen()
        : (document).webkitExitFullscreen?.() ||
          (document).mozCancelFullScreen?.()
      return
    }

    // 否则进入指定编辑器全屏
    // const wrapper = codeEditors.value[idx]?.$el
    const wrapper = document.querySelectorAll('.code-wrapper')[idx]
    codeEditors.value[idx] && codeEditors.value[idx]
    wrapper?.requestFullscreen
      ? wrapper.requestFullscreen()
      : (wrapper).webkitRequestFullscreen?.() ||
        (wrapper).mozRequestFullScreen?.()
  })
}
const toggleRemark = idx => {
  remarkVisible.value[idx] = !remarkVisible.value[idx]
}
</script>

<style scoped lang="less">
.remark-area {
  background: #fafafa;
  border-top: 1px dashed #ccc;
  padding: 12px;
}
.page {
    height: 100%;
    overflow-x: hidden;
    display: flex;
    flex-direction: column;
    align-items: center;
}

.page-content {
    max-width: 960px;
    width: 70vw;
    margin: 0 auto;
    font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
}

.header {
    width: 100%;
    position: sticky;
    top: 0;
    background: #fff;
    padding: 10px 0;
    z-index: 99999;
    display: flex;
    justify-content: center;
}

.header.shadow {
    border-bottom: 1px solid #304156;
    box-shadow: 0 2px 12px rgba(48, 65, 86, .3);
    transition: box-shadow .3s;
    background: #f5f6f7;
}

.header-content {
    max-width: 960px;
    width: 70vw;
    display: flex;
    align-items: center;
    justify-content: space-between;
}

h1 {
    text-align: center;
}

.top-bar {
    display: flex;
    align-items: center;
}

.primary {
    background: #409eff;
    color: #fff;
    border: none;
    padding: 6px 12px;
    border-radius: 4px;
    cursor: pointer;
}

.tip {
    color: #67c23a;
    margin-left: 8px;
}

.question {
    margin-bottom: 40px;
    border: 1px solid #e4e7ed;
    border-radius: 6px;
    overflow: hidden;
}

.question-bg {
    background: #fafafa;
}

.code-wrapper {
    position: relative;
    background: white;
}

.mini-bar {
    position: absolute;
    right: 8px;
    top: 0px;
    display: flex;
    gap: 6px;
}

.mini-bar button {
    border: 1px solid #dcdfe6;
    background: #fff;
    padding: 4px 8px;
    border-radius: 3px;
    cursor: pointer;
    font-size: 12px;
}

.mini-bar button:hover {
    background: #ecf5ff;
    border-color: #409eff;
    color: #409eff;
}

:deep(.ql-editor) {
    font-family: Consolas, Monaco, monospace;
    font-size: 14px;
    min-height: 180px;
}
</style>